#include <stdio.h>
#include "BF.h"


int HDF_OpenFile( char* fileName, FILE** file )
{
	*file = fopen ( fileName, "rb+" );

	if ( *file == NULL )
	{
		BF_errno = BFE_CANNOTOPENFILE;
		return BFE_CANNOTOPENFILE;
	}
	else
	{
		BF_errno = BFE_OK;
		return BFE_OK;
	}
}

int HDF_CloseFile ( FILE* file )
{
	int result;

	result = fclose ( file );

	if ( result == 0 )
	{
		BF_errno = BFE_OK;
		return BFE_OK;
	}
	else
	{
		BF_errno = BFE_CANNOTCLOSEFILE;
		return BFE_CANNOTCLOSEFILE;
	}
}

int HDF_CreateFile ( char* fileName )
{
	FILE *file;
	
	file = fopen( fileName, "wb" );

	if ( file == NULL )
	{
		BF_errno = BFE_CANNOTCREATEFILE;
		return BFE_CANNOTCREATEFILE;
	}
	else
	{
		BF_errno = BFE_OK;
		fclose ( file );
		return BFE_OK;
	}

}

int HDF_DestroyFile ( char* fileName )
{
	int result;

	result = remove ( fileName );
	
	if ( result == 0 )
	{
		BF_errno = BFE_OK;
		return BFE_OK;
	}
	else
	{
		BF_errno = BFE_CANNOTDESTROYFILE;
		return BFE_CANNOTDESTROYFILE;
	}
}

bool HDF_ExistsFile ( char* fileName )
{
	FILE *file;

	file = fopen ( fileName, "rb" );

	if ( file == NULL )
	{
		return false;	
	}
	else
	{
		fclose ( file );
		return true;
	}
}

int HDF_ReadBlock( int blockIndex , char* blockBuf, FILE* file )
{
	size_t elementsRead;

	fseek ( file, blockIndex * BF_BLOCK_SIZE, SEEK_SET );
	elementsRead = fread ( blockBuf, BF_BLOCK_SIZE, 1, file );

	if ( elementsRead == 1)
	{
		BF_errno = BFE_OK;
		return BFE_OK;
	}
	else if ( feof ( file ) )
	{
		BF_errno = BFE_EOF;
		return BFE_EOF;
	}
	else
	{
		BF_errno = BFE_INCOMPLETEREAD;
		return BFE_INCOMPLETEREAD;
	}
}

int HDF_WriteBlock ( int blockIndex, char* blockBuf, FILE* file )
{
	size_t elementsWrote;

	fseek ( file, blockIndex * BF_BLOCK_SIZE, SEEK_SET );
	elementsWrote = fwrite ( blockBuf, BF_BLOCK_SIZE, 1, file );

	if ( elementsWrote == 1)
	{
		BF_errno = BFE_OK;
		return BFE_OK;
	}
	else
	{
		BF_errno = BFE_INCOMPLETEWRITE;
		return BFE_INCOMPLETEWRITE;
	}
}
